package selef.xiafan.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import selef.xiafan.dao.*;
import selef.xiafan.dto.CommentDTO;
import selef.xiafan.entity.Comment;
import selef.xiafan.entity.CommentImage;
import selef.xiafan.entity.CommentOrder;
import selef.xiafan.entity.Image;
import selef.xiafan.entity.order.Order;
import selef.xiafan.service.ICommentService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author xiafan
 * @version 1.0
 * @date 2021/9/26 11:18
 */
@Service
public class ICommentServiceImpl implements ICommentService {
    @Autowired
    CommentDao commentDao;
    @Autowired
    CommentOrderDao commentOrderDao;
    @Autowired
    CommentImageDao commentImageDao;
    @Autowired
    ImageDao imageDao;

    @Override
    public Integer add(CommentDTO commentDTO) {
        Comment comment = commentDTO.getComment();
        CommentOrder commentOrder = commentDTO.getCommentOrder();


        String randomId = UUID.randomUUID().toString().substring(0, 7);
        comment.setCommentId(randomId);
        commentDao.save(comment);

        commentOrder.setCommentId(randomId);
        commentOrderDao.save(commentOrder);

        if(commentDTO.getPhotoName()!=null){
            String address = "D://WorkFile//IdeaProject//Repair//4S-system//src//main//resources//static//uploadImage//"+commentDTO.getPhotoName();
            Image bySrc = imageDao.findBySrc(address);
            CommentImage commentImage = new CommentImage();
            commentImage.setCommentId(randomId);
            commentImage.setImageId(bySrc.getImageId());
            commentImageDao.save(commentImage);
        }
        return 1;
    }

    @Override
    public Object findComment(Order order) {
        String orderId = order.getOrderId();
        Map<String, Object> hashMap = new HashMap<>();
        // 查询评论的两张中间表
        CommentOrder commentOrder = commentOrderDao.findByOrderId(orderId);
        if(commentOrder == null){
            return "用户还未评论";
        }
        String commentId = commentOrder.getCommentId();


        CommentImage commentImage = commentImageDao.findByCommentId(commentId);
        if(commentImage!=null){
            String imageId = commentImage.getImageId();
            Image image = imageDao.findByImageId(imageId);
            hashMap.put("image",image);
        }
        Comment comment = commentDao.findByCommentId(commentId);
        hashMap.put("comment",comment);
        return hashMap;
    }

    @Override
    public List<Comment> getAll() {
        List<Comment> all = commentDao.findAll();
        return all;
    }
}
